package name.huzhenbo.java.patterns.singleton;

/**
 * The memory model of JVM make this fail: in the absence of synchronization, reading a "published" object reference does
 * not guarantee that a thread will see all of the data that were stored in memory prior to the publication of object
 * reference.  (e.g. instance is not null, but the data is not ready in memory, and invocation of the method of instance will
 * fail.)
 * <p/>
 * Use synchronization to ensure the change in a thread will be observed by other threads.
 */
class NotSafeDoubleCheckSingleton {

    private static NotSafeDoubleCheckSingleton instance;

    public static NotSafeDoubleCheckSingleton getInstance() {
        // Intent to avoid synchronization cost for every invocation.
        if (instance == null) {
            synchronized (NotSafeDoubleCheckSingleton.class) {
                if (instance == null) {
                    instance = new NotSafeDoubleCheckSingleton();
                }
            }
        }
        return instance;
    }
}
